<template>
  <div class="app-container">
    <div class="container-fluid py-4">
      <div class="row g-4">
        <!-- 侧边导航 - 在大屏幕显示为左侧，小屏幕显示为顶部 -->
        <div class="col-12 col-lg-3 mb-4">
          <!-- 大屏幕左侧标签 -->
          <div class="card shadow-sm d-none d-lg-block h-100">
            <div class="card-body p-0">
              <el-tabs v-model="activeTab" tab-position="left" class="h-100">
                <el-tab-pane name="account" label="账号信息">
                  <!-- 标签内容由右侧主区域显示 -->
                </el-tab-pane>
                <el-tab-pane name="security" label="安全设置">
                  <!-- 标签内容由右侧主区域显示 -->
                </el-tab-pane>
              </el-tabs>
            </div>
          </div>

          <!-- 小屏幕顶部标签 -->
          <div class="card shadow-sm d-lg-none mb-2">
            <div class="card-body p-2">
              <el-tabs v-model="activeTab" class="mobile-tabs">
                <el-tab-pane name="account" label="账号信息"></el-tab-pane>
                <el-tab-pane name="security" label="安全设置"></el-tab-pane>
              </el-tabs>
            </div>
          </div>
        </div>

        <!-- 主内容区域 -->
        <div class="col-12 col-lg-9">
          <!-- 账号信息卡片 -->
          <div v-if="activeTab === 'account'" class="card shadow-sm mb-4">
            <div class="card-body">
              <div class="row">
                <!-- 头像和昵称部分 -->
                <div class="col-12 col-md-4 text-center mb-4 mb-md-0">
                  <div class="position-relative d-inline-block">
                    <el-avatar :src="userProfile.avatar" :size="120" class="border shadow-sm" />
                    <el-button
                      type="info"
                      class="position-absolute bottom-0 end-0 rounded-circle"
                      circle
                      :icon="Camera"
                      size="small"
                      @click="triggerFileUpload"
                    />
                    <input ref="fileInput" type="file" class="d-none" @change="handleFileChange" />
                  </div>
                  <h5 class="mt-3 mb-1">{{ userProfile.nickname }}</h5>
                  <div class="d-flex align-items-center justify-content-center">
                    <small class="text-muted">编辑资料</small>
                    <el-icon
                      class="ms-1 cursor-pointer"
                      @click="handleOpenDialog(DialogType.ACCOUNT)"
                    >
                      <Edit />
                    </el-icon>
                  </div>
                </div>

                <!-- 用户信息描述 -->
                <div class="col-12 col-md-8">
                  <h5 class="border-bottom pb-2 mb-3">个人资料</h5>
                  <div class="row g-3">
                    <div class="col-12 col-sm-6">
                      <div class="d-flex align-items-center">
                        <div class="icon-box me-2 d-flex align-items-center justify-content-center">
                          <el-icon><User /></el-icon>
                        </div>
                        <div>
                          <div class="small text-muted">用户名</div>
                          <div>
                            {{ userProfile.username }}
                            <el-icon v-if="userProfile.gender === 1" class="ms-1 text-primary">
                              <Male />
                            </el-icon>
                            <el-icon v-else class="ms-1 text-danger">
                              <Female />
                            </el-icon>
                          </div>
                        </div>
                      </div>
                    </div>

                    <div class="col-12 col-sm-6">
                      <div class="d-flex align-items-center">
                        <div class="icon-box me-2 d-flex align-items-center justify-content-center">
                          <el-icon><Phone /></el-icon>
                        </div>
                        <div>
                          <div class="small text-muted">手机号码</div>
                          <div>{{ userProfile.mobile || "未设置" }}</div>
                        </div>
                      </div>
                    </div>

                    <div class="col-12 col-sm-6">
                      <div class="d-flex align-items-center">
                        <div class="icon-box me-2 d-flex align-items-center justify-content-center">
                          <el-icon><Message /></el-icon>
                        </div>
                        <div>
                          <div class="small text-muted">邮箱</div>
                          <div>{{ userProfile.email || "未设置" }}</div>
                        </div>
                      </div>
                    </div>

                    <div class="col-12 col-sm-6">
                      <div class="d-flex align-items-center">
                        <div class="icon-box me-2 d-flex align-items-center justify-content-center">
                          <div class="i-svg:tree"></div>
                        </div>
                        <div>
                          <div class="small text-muted">部门</div>
                          <div>{{ userProfile.deptName || "未设置" }}</div>
                        </div>
                      </div>
                    </div>

                    <div class="col-12 col-sm-6">
                      <div class="d-flex align-items-center">
                        <div class="icon-box me-2 d-flex align-items-center justify-content-center">
                          <div class="i-svg:role"></div>
                        </div>
                        <div>
                          <div class="small text-muted">角色</div>
                          <div>{{ userProfile.roleNames || "未设置" }}</div>
                        </div>
                      </div>
                    </div>

                    <div class="col-12 col-sm-6">
                      <div class="d-flex align-items-center">
                        <div class="icon-box me-2 d-flex align-items-center justify-content-center">
                          <el-icon><Timer /></el-icon>
                        </div>
                        <div>
                          <div class="small text-muted">创建日期</div>
                          <div>{{ userProfile.createTime || "未知" }}</div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 安全设置卡片 -->
          <div v-if="activeTab === 'security'" class="card shadow-sm">
            <div class="card-body">
              <h5 class="border-bottom pb-2 mb-4">安全设置</h5>

              <!-- 账户密码 -->
              <div class="row align-items-center py-3 border-bottom">
                <div class="col-12 col-md-8">
                  <h6 class="mb-1">账户密码</h6>
                  <p class="text-muted mb-md-0 small">定期修改密码有助于保护账户安全</p>
                </div>
                <div class="col-12 col-md-4 text-md-end">
                  <el-button
                    type="primary"
                    plain
                    size="small"
                    @click="() => handleOpenDialog(DialogType.PASSWORD)"
                  >
                    修改
                  </el-button>
                </div>
              </div>

              <!-- 绑定手机 -->
              <div class="row align-items-center py-3 border-bottom">
                <div class="col-12 col-md-8">
                  <h6 class="mb-1">绑定手机</h6>
                  <p class="text-muted mb-md-0 small">
                    {{ userProfile.mobile ? `已绑定手机号：${userProfile.mobile}` : "未绑定手机" }}
                  </p>
                </div>
                <div class="col-12 col-md-4 text-md-end">
                  <el-button
                    type="primary"
                    plain
                    size="small"
                    @click="() => handleOpenDialog(DialogType.MOBILE)"
                  >
                    {{ userProfile.mobile ? "更换" : "绑定" }}
                  </el-button>
                </div>
              </div>

              <!-- 绑定邮箱 -->
              <div class="row align-items-center py-3">
                <div class="col-12 col-md-8">
                  <h6 class="mb-1">绑定邮箱</h6>
                  <p class="text-muted mb-md-0 small">
                    {{ userProfile.email ? `已绑定邮箱：${userProfile.email}` : "未绑定邮箱" }}
                  </p>
                </div>
                <div class="col-12 col-md-4 text-md-end">
                  <el-button
                    type="primary"
                    plain
                    size="small"
                    @click="() => handleOpenDialog(DialogType.EMAIL)"
                  >
                    {{ userProfile.email ? "更换" : "绑定" }}
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 弹窗 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" :width="500" class="profile-dialog">
      <!-- 账号资料 -->
      <el-form
        v-if="dialog.type === DialogType.ACCOUNT"
        ref="userProfileFormRef"
        :model="userProfileForm"
        :label-width="100"
      >
        <el-form-item label="昵称">
          <el-input v-model="userProfileForm.nickname" />
        </el-form-item>
        <el-form-item label="性别">
          <Dict v-model="userProfileForm.gender" code="gender" />
        </el-form-item>
      </el-form>

      <!-- 修改密码 -->
      <el-form
        v-if="dialog.type === DialogType.PASSWORD"
        ref="passwordChangeFormRef"
        :model="passwordChangeForm"
        :rules="passwordChangeRules"
        :label-width="100"
      >
        <el-form-item label="原密码" prop="oldPassword">
          <el-input v-model="passwordChangeForm.oldPassword" type="password" show-password />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordChangeForm.newPassword" type="password" show-password />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="passwordChangeForm.confirmPassword" type="password" show-password />
        </el-form-item>
      </el-form>

      <!-- 绑定手机 -->
      <el-form
        v-else-if="dialog.type === DialogType.MOBILE"
        ref="mobileBindingFormRef"
        :model="mobileUpdateForm"
        :rules="mobileBindingRules"
        :label-width="100"
      >
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="mobileUpdateForm.mobile" style="width: 250px" />
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <el-input v-model="mobileUpdateForm.code" style="width: 250px">
            <template #append>
              <el-button class="ml-5" :disabled="mobileCountdown > 0" @click="handleSendMobileCode">
                {{ mobileCountdown > 0 ? `${mobileCountdown}s后重新发送` : "发送验证码" }}
              </el-button>
            </template>
          </el-input>
        </el-form-item>
      </el-form>

      <!-- 绑定邮箱 -->
      <el-form
        v-else-if="dialog.type === DialogType.EMAIL"
        ref="emailBindingFormRef"
        :model="emailUpdateForm"
        :rules="emailBindingRules"
        :label-width="100"
      >
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="emailUpdateForm.email" style="width: 250px" />
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <el-input v-model="emailUpdateForm.code" style="width: 250px">
            <template #append>
              <el-button class="ml-5" :disabled="emailCountdown > 0" @click="handleSendEmailCode">
                {{ emailCountdown > 0 ? `${emailCountdown}s后重新发送` : "发送验证码" }}
              </el-button>
            </template>
          </el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialog.visible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import UserAPI, {
  UserProfileVO,
  PasswordChangeForm,
  MobileUpdateForm,
  EmailUpdateForm,
  UserProfileForm,
} from "@/api/system/user";

import FileAPI from "@/api/file";

import { Camera } from "@element-plus/icons-vue";
import { useUserStore } from "@/store";

const userProfile = ref<UserProfileVO>({});
const userStore = useUserStore();
const activeTab = ref("account"); // 默认显示账号信息标签页

const enum DialogType {
  ACCOUNT = "account",
  PASSWORD = "password",
  MOBILE = "mobile",
  EMAIL = "email",
}

const dialog = reactive({
  visible: false,
  title: "",
  type: "" as DialogType, // 修改账号资料,修改密码、绑定手机、绑定邮箱
});

const userProfileForm = reactive<UserProfileForm>({});
const passwordChangeForm = reactive<PasswordChangeForm>({});
const mobileUpdateForm = reactive<MobileUpdateForm>({});
const emailUpdateForm = reactive<EmailUpdateForm>({});

const mobileCountdown = ref(0);
const mobileTimer = ref();

const emailCountdown = ref(0);
const emailTimer = ref();

// 修改密码校验规则
const passwordChangeRules = {
  oldPassword: [{ required: true, message: "请输入原密码", trigger: "blur" }],
  newPassword: [{ required: true, message: "请输入新密码", trigger: "blur" }],
  confirmPassword: [{ required: true, message: "请再次输入新密码", trigger: "blur" }],
};

// 手机号校验规则
const mobileBindingRules = {
  mobile: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
  code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
};

// 邮箱校验规则
const emailBindingRules = {
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    {
      pattern: /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/,
      message: "请输入正确的邮箱地址",
      trigger: "blur",
    },
  ],
  code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
};

/**
 * 打开弹窗
 * @param type 弹窗类型 ACCOUNT: 账号资料 PASSWORD: 修改密码 MOBILE: 绑定手机 EMAIL: 绑定邮箱
 */
const handleOpenDialog = (type: DialogType) => {
  dialog.type = type;
  dialog.visible = true;
  switch (type) {
    case DialogType.ACCOUNT:
      dialog.title = "账号资料";
      // 初始化表单数据
      userProfileForm.id = userProfile.value.id;
      userProfileForm.nickname = userProfile.value.nickname;
      userProfileForm.gender = userProfile.value.gender;
      break;
    case DialogType.PASSWORD:
      dialog.title = "修改密码";
      break;
    case DialogType.MOBILE:
      dialog.title = "绑定手机";
      break;
    case DialogType.EMAIL:
      dialog.title = "绑定邮箱";
      break;
  }
};

/**
 * 发送手机验证码
 */
function handleSendMobileCode() {
  if (!mobileUpdateForm.mobile) {
    ElMessage.error("请输入手机号");
    return;
  }
  // 验证手机号格式
  const reg = /^1[3-9]\d{9}$/;
  if (!reg.test(mobileUpdateForm.mobile)) {
    ElMessage.error("手机号格式不正确");
    return;
  }
  // 发送短信验证码
  UserAPI.sendMobileCode(mobileUpdateForm.mobile).then(() => {
    ElMessage.success("验证码发送成功");

    // 倒计时 60s 重新发送
    mobileCountdown.value = 60;
    mobileTimer.value = setInterval(() => {
      if (mobileCountdown.value > 0) {
        mobileCountdown.value -= 1;
      } else {
        clearInterval(mobileTimer.value!);
      }
    }, 1000);
  });
}

/**
 * 发送邮箱验证码
 */
function handleSendEmailCode() {
  if (!emailUpdateForm.email) {
    ElMessage.error("请输入邮箱");
    return;
  }
  // 验证邮箱格式
  const reg = /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/;
  if (!reg.test(emailUpdateForm.email)) {
    ElMessage.error("邮箱格式不正确");
    return;
  }

  // 发送邮箱验证码
  UserAPI.sendEmailCode(emailUpdateForm.email).then(() => {
    ElMessage.success("验证码发送成功");
    // 倒计时 60s 重新发送
    emailCountdown.value = 60;
    emailTimer.value = setInterval(() => {
      if (emailCountdown.value > 0) {
        emailCountdown.value -= 1;
      } else {
        clearInterval(emailTimer.value!);
      }
    }, 1000);
  });
}

/**
 * 提交表单
 */
const handleSubmit = async () => {
  if (dialog.type === DialogType.ACCOUNT) {
    UserAPI.updateProfile(userProfileForm).then(() => {
      ElMessage.success("账号资料修改成功");
      dialog.visible = false;
      loadUserProfile();
    });
  } else if (dialog.type === DialogType.PASSWORD) {
    if (passwordChangeForm.newPassword !== passwordChangeForm.confirmPassword) {
      ElMessage.error("两次输入的密码不一致");
      return;
    }
    UserAPI.changePassword(passwordChangeForm).then(() => {
      ElMessage.success("密码修改成功");
      dialog.visible = false;
    });
  } else if (dialog.type === DialogType.MOBILE) {
    UserAPI.bindOrChangeMobile(mobileUpdateForm).then(() => {
      ElMessage.success("手机号绑定成功");
      dialog.visible = false;
      loadUserProfile();
    });
  } else if (dialog.type === DialogType.EMAIL) {
    UserAPI.bindOrChangeEmail(emailUpdateForm).then(() => {
      ElMessage.success("邮箱绑定成功");
      dialog.visible = false;
      loadUserProfile();
    });
  }
};

const fileInput = ref<HTMLInputElement | null>(null);

const triggerFileUpload = () => {
  fileInput.value?.click();
};

const handleFileChange = async (event: Event) => {
  const target = event.target as HTMLInputElement;
  const file = target.files ? target.files[0] : null;
  if (file) {
    // 调用文件上传API
    try {
      const data = await FileAPI.uploadFile(file);
      // 更新用户头像
      userProfile.value.avatar = data.url;
      // 更新用户信息
      await UserAPI.updateProfile({
        avatar: data.url,
      });
      await userStore.getUserInfo();
    } catch (error) {
      console.error("头像上传失败：" + error);
      ElMessage.error("头像上传失败");
    }
  }
};

/** 加载用户信息 */
const loadUserProfile = async () => {
  const data = await UserAPI.getProfile();
  userProfile.value = data;
};

onMounted(async () => {
  if (mobileTimer.value) {
    clearInterval(mobileTimer.value);
  }
  if (emailTimer.value) {
    clearInterval(emailTimer.value);
  }
  await loadUserProfile();
});
</script>

<style lang="scss" scoped>
.app-container {
  min-height: calc(100vh - 500px - 2rem);
  background: var(--el-bg-color);
  padding-bottom: 1rem;
  margin-top: 16px;
  border-radius: 15px;
}

.hasTagsView {
  .app-container {
    min-height: calc(100vh - 84px - 2rem);
  }
}

// 卡片样式
.card {
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 0.5rem;
  background-color: var(--el-bg-color-overlay);
  transition: all 0.3s ease;

  &:hover {
    box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.08) !important;
  }

  .card-body {
    padding: 1.5rem;
  }
}

// 图标盒子样式
.icon-box {
  width: 36px;
  height: 36px;
  border-radius: 8px;
  background-color: var(--el-color-primary-light-9);
  color: var(--el-color-primary);
}

// 头像样式
.el-avatar {
  border: 2px solid var(--el-border-color-lighter) !important;
  background-color: var(--el-bg-color);
}

// 对话框样式
:deep(.profile-dialog) {
  .el-dialog__header {
    margin: 0;
    padding: 1rem 1.5rem;
    border-bottom: 1px solid var(--el-border-color-lighter);
  }

  .el-dialog__body {
    padding: 1.5rem;
  }

  .el-dialog__footer {
    padding: 1rem 1.5rem;
    border-top: 1px solid var(--el-border-color-lighter);
  }
}

// 小屏幕标签样式优化
.mobile-tabs {
  :deep(.el-tabs__header) {
    margin-bottom: 0;
  }

  :deep(.el-tabs__nav-wrap) {
    padding: 0 0.5rem;
  }

  :deep(.el-tabs__nav) {
    width: 100%;
    display: flex;
  }

  :deep(.el-tabs__item) {
    flex: 1;
    text-align: center;
    font-size: 0.95rem;
    padding: 0 0.5rem;
    height: 40px;
    line-height: 40px;
    transition: all 0.3s;

    &.is-active {
      font-weight: 600;
    }
  }

  :deep(.el-tabs__active-bar) {
    height: 3px;
    border-radius: 3px;
  }
}

// 响应式调整
@media (max-width: 768px) {
  .app-container {
    padding-bottom: 0.5rem;
  }

  .card .card-body {
    padding: 1.25rem;
  }

  .icon-box {
    width: 32px;
    height: 32px;
  }

  h5 {
    font-size: 1.1rem;
  }

  h6 {
    font-size: 1rem;
  }

  .row.align-items-center {
    padding-top: 1rem;
    padding-bottom: 1rem;
  }

  .card.shadow-sm.d-lg-none {
    border-radius: 0.75rem;
    margin-left: 0.5rem;
    margin-right: 0.5rem;
    border: none;

    .card-body {
      padding: 0.5rem 0;
    }
  }
}
</style>
